<script lang="ts" setup>
import { ref, onMounted } from "vue";
import { defineAsyncComponent } from "vue";
import { SForm } from "#components";
import { Model } from "../user/model";
// 编辑当前用户资料时，隐藏角色
Model.roles.formHide = "all";
// 编辑当前用户资料时，隐藏禁用
Model.disabled.formHide = "all";

const reactive_Model = reactive(Model);

const PageConfig = {
  //被操作实体的名称
  entity: "user",
  entityName: "用户",
  api: {
    //修改
    edit: "/user/edit",
  },
};

// 标记客户端环境
const isClient = ref(false);

// 动态导入组件，禁用SSR
const AvatarCropper = defineAsyncComponent({
  loader: () => import("~/components/SUI/S-avatar.vue"),
  suspensible: false, // 关键：禁止在服务端渲染该组件，使用 suspensible 替代 ssr
});

const editInfoFormRef = ref<InstanceType<typeof SForm> | null>(null);
const currentUser = useCurrentUserStore().currentUser;
const formData = reactive({
  ...currentUser,
});
const action = ref("edit");

// 加载表单下载列表
const getData = async () => {
  try {
    // 加载下拉列表--岗位
    const res_position = await $fetch(`/api/position/all`);

    reactive_Model.positions.options = res_position.data.map((item) => ({
      label: item.name,
      value: item._id,
    }));

    // 加载下拉列表--性别
    reactive_Model.gender.options = await getDicList("gender");

    // 加载下拉树--部门
    const res_department: {
      [key: string]: any;
    }[] = await $fetch(`/api/system/list`, {
      query: {
        name: "department",
      },
    });

    if (Array.isArray(res_department) && res_department.length) {
      reactive_Model.department.treeData = JSON.parse(
        res_department[0].content
      );
    }
  } catch (error) {}
};

const save = async () => {
  if (editInfoFormRef.value) {
    // 调用子组件的方法
    editInfoFormRef.value.submitForm(editInfoFormRef.value.formRef);
  }
};

const saveOK = async () => {
  action.value = "detail";

  useCurrentUserStore().setCurrentUser({
    ...currentUser,
    ...formData,
  });
};

onMounted(() => {
  isClient.value = true; // 确保在客户端挂载后才显示组件
  getData();
});
</script>
<template>
  <S-form
    ref="editInfoFormRef"
    hideHandle
    class="m-4"
    :action="action"
    :disabled="action === 'detail'"
    :saveOK="saveOK"
    :saveAPI="PageConfig.api.edit"
    v-model="formData"
    :Model="reactive_Model"
  >
    <template #avatar>
      <AvatarCropper
        :disabled="action === 'detail'"
        v-if="isClient"
        v-model="formData.avatar"
      />
    </template>
  </S-form>
  <div class="flex justify-center p4" v-show="action === 'edit'">
    <el-button @click="action = 'detail'">取消</el-button>
    <el-button type="primary" @click="save">保存</el-button>
  </div>
  <div class="flex justify-center p4" v-show="action === 'detail'">
    <el-button type="primary" @click="action = 'edit'">编辑</el-button>
  </div>
</template>
